<?php

class BookFlight extends CI_Controller {

	function __construct() {
		parent::__construct();
		$this->load->model('payment_api');
	}

	public function index() {
		if (!$this->session->userdata('logged_in')) {
			redirect('login');
		}

		$this->form_validation->set_error_delimiters('<div class="error"><li>', '</li></div>');

		$this->form_validation->set_rules('pax_phone', $this->lang->line('phone'), 'required|min_length[7]|max_length[20]');
		$this->form_validation->set_rules('pax_tc_number', $this->lang->line('tc_identity'), 'trim|numeric|exact_length[11]');
		$this->form_validation->set_rules('pax_email', $this->lang->line('e_mail'), 'trim|valid_email');
		$this->form_validation->set_rules('pax_corporate_pin', $this->lang->line('corporate_pin'), 'trim|max_length[11]');

		$this->form_validation->set_rules('pax_sex[]', $this->lang->line('sex'), 'required');
		$this->form_validation->set_rules('pax_name[]', $this->lang->line('name'), 'required|min_length[2]|max_length[20]');
		$this->form_validation->set_rules('pax_surname[]', $this->lang->line('surname'), 'required|min_length[2]|max_length[20]');
		if ($this->session->userdata('search_form_infants') > 0) {
			$this->form_validation->set_rules('pax_dob[]', $this->lang->line('date_of_birth'), 'required|callback_check_infant_age');
		}
		//
		$this->form_validation->set_rules('pax_miles_number[]', $this->lang->line('miles_smiles'), 'trim|callback_check_miles');
		$this->form_validation->set_rules('pax_wheel_chair[]', $this->lang->line('wheel_chair'), 'required');

		/* 3D Secure does not this fields
		 $this->form_validation->set_rules('card_type', 'card_type', 'required');
		 $this->form_validation->set_rules('card_number', 'card_number', 'required,trim');
		 $this->form_validation->set_rules('card_cvc2', 'card_cvc2', 'required,trim');
		 $this->form_validation->set_rules('card_expiry_month', 'card_expiry_month', 'required');
		 $this->form_validation->set_rules('card_expiry_year', 'card_expiry_year', 'required');
		 */

		$submit = $this->input->post('submit');
		if ($submit[0] != 'R') {
			$this->form_validation->set_rules('receipt_is_company', 'receipt_is_company', 'trim');
			$this->form_validation->set_rules('receipt_address', $this->lang->line('adress'), 'required|max_length[60]');
			$this->form_validation->set_rules('receipt_city', $this->lang->line('city'), 'required|max_length[30]');
			$this->form_validation->set_rules('receipt_country', $this->lang->line('country'), 'required|max_length[30]');
			$this->form_validation->set_rules('receipt_zip_code', $this->lang->line('zip_code'), 'required|max_length[10]');
			$this->form_validation->set_rules('receipt_tc_number', $this->lang->line('tc_identity_inv'), 'trim|numeric|exact_length[11]');
			if ($this->input->post('receipt_is_company') == true) {
				$this->form_validation->set_rules('receipt_company_name', $this->lang->line('company_name'), 'required|max_length[60');
				$this->form_validation->set_rules('receipt_tax_department', $this->lang->line('tax_department'), 'required|max_length[60]');
				$this->form_validation->set_rules('receipt_tax_number', $this->lang->line('tax_number'), 'required|numeric|max_length[15]');
			}
		}
		$this->form_validation->set_rules('read_understood', $this->lang->line('read_understood'), 'required');
		if ($this->form_validation->run() == FALSE) {  // display fare information and ask for passenger details.
			$sel_depart = $this->input->get('sel_depart');
			if (!empty($sel_depart)) {
				$flight = explode('|', $this->input->get('sel_depart')); //1|TK2170|H|15-1800|IST|ESB|false
				$this->session->set_userdata('first_flight_time', $flight[3]);
				$segment_data = array(
				array(
                        'flightNumber' => $flight[1],
                        'flightClass' => $flight[2],
                        'date' => $this->session->userdata('search_form_depart_on'),
                        'origin' => $flight[4],
                        'destination' => $flight[5],
                        'isConnected' => ($flight[0]==2)?1:0));

				if ($flight[0] === '2') {
					$flight_date = $this->session->userdata('search_form_depart_on');
					if (strlen($flight[3]) > 4) {
						$flight_date = $this->session->userdata('search_form_depart_on_ui');
						if (substr($flight_date, 0, 2) != substr($flight[9], 0, 2)) {
							$flight_date = date('dmY', strtotime(date("Y-m-d", strtotime($flight_date)) . " +1 day"));
						} else {
							$flight_date = $this->session->userdata('search_form_depart_on');
						}
					}
					array_push($segment_data, array(
                        'flightNumber' => $flight[7],
                        'flightClass' => $flight[8],
                        'date' => $flight_date,
                        'origin' => $flight[10],
                        'destination' => $flight[11],
                        'isConnected' => FALSE));
				}
				if ($this->session->userdata('search_form_trip_type') === 'RT') {
					$flight = explode('|', $this->input->get('sel_return')); //1|TK2170|H|15-1800|IST|ESB|false
					array_push($segment_data, array(
                        'flightNumber' => $flight[1],
                        'flightClass' => $flight[2],
                        'date' => $this->session->userdata('search_form_return_on'),
                        'origin' => $flight[4],
                        'destination' => $flight[5],
                        'isConnected' => ($flight[0]==2)?1:0));

					if ($flight[0] === '2') {
						$flight_date = $this->session->userdata('search_form_return_on');
						if (strlen($flight[3]) > 4) {
							$flight_date = $this->session->userdata('search_form_return_on_ui');
							if (substr($flight_date, 0, 2) != substr($flight[9], 0, 2)) {
								$flight_date = date('dmY', strtotime(date("Y-m-d", strtotime($flight_date)) . " +1 day"));
							} else {
								$flight_date = $this->session->userdata('search_form_return_on');
							}
						}
						array_push($segment_data, array(
                            'flightNumber' => $flight[7],
                            'flightClass' => $flight[8],
                            'date' => $flight_date,
                            'origin' => $flight[10],
                            'destination' => $flight[11],
                            'isConnected' => FALSE));
					}
				}
				// Store segement data to use while creating ticket
				$this->session->set_userdata('segment_data', $segment_data);
			}
			$fares_xml = $this->websdom_api->call_get_fares($this->session->userdata('agency_tk_user'), $this->session->userdata('agency_tk_pass'), $this->session->userdata('segment_data'), $this->session->userdata('search_form_adults'), $this->session->userdata('search_form_children'), $this->session->userdata('search_form_infants'), $this->session->userdata('search_form_elders'), $this->session->userdata('search_form_students'), $this->session->userdata('search_form_military'), $this->session->userdata('search_form_cip'));

			$exception = $fares_xml->xpath('//Exception');
			if (count($exception) > 0) {
				$err  = '<pre>ERROR OCCURED<BR>-------------';
				$err .= '<BR>Code       :' . $exception[0]->code;
				$err .= '<BR>Descriptino:' . $exception[0]->description;
				$err .= '<BR>Detail     :' . $exception[0]->details;
				$err .= '</pre>';
				show_error('İşleminizde bir hatası oluştu. Lütfen tekrar deneyiniz.<br/>'.$err);
			} else {

				$data_fare['fare_arr'] = $this->get_fares_with_du($fares_xml->xpath('//fareItem'),
				$fares_xml->xpath('//grandTotal'),
				$this->session->userdata('segment_data'),
				$this->session->userdata('search_form_adults'),
				$this->session->userdata('search_form_children'),
				$this->session->userdata('search_form_students'),
				$this->session->userdata('search_form_military'),
				$this->session->userdata('search_form_elders'));


				$this->template->write('title', 'Profile!');
				$this->template->write_view('left_side_bar_top', 'book_flight_fare', $data_fare);
				$this->template->write_view('left_side_bar_bottom', 'content/3dsecure');
				$this->template->write_view('content', 'book_flight_profile');
				$this->template->render();
			}
		} else { // create ticket
			// var_dump($this->session->userdata);  exit;
			// prepare data...
			$session_array = array(
                'pax_type' => $this->input->post('pax_type'),
                'pax_name' => $this->input->post('pax_name'),
                'pax_surname' => $this->input->post('pax_surname'),
                'pax_sex' => $this->input->post('pax_sex'),
                'pax_phone' => $this->input->post('pax_phone'),
                'pax_tc_number' => $this->input->post('pax_tc_number'),
                'pax_email' => $this->input->post('pax_email'),
                'pax_miles_number' => $this->input->post('pax_miles_number'),
				'pax_corporate_pin' => $this->input->post('pax_corporate_pin'),
				'pax_wheel_chair' => $this->input->post('pax_wheel_chair'),
				'receipt_is_company' => $this->input->post('receipt_is_company'),
                'receipt_address' => $this->input->post('receipt_address'),
                'receipt_city' => $this->input->post('receipt_city'),
                'receipt_country' => $this->input->post('receipt_country'),
                'receipt_zip_code' => $this->input->post('receipt_zip_code'),
                'receipt_company_name' => $this->input->post('receipt_company_name'),
                'receipt_tax_department' => $this->input->post('receipt_tax_department'),
                'receipt_tax_number' => $this->input->post('receipt_tax_number'),
                'receipt_tc_number' => $this->input->post('receipt_tc_number'),
			);
			$this->session->set_userdata($session_array);


			$pax_type = $this->input->post('pax_type');
			$pax_name = $this->input->post('pax_name');
			$pax_surname = $this->input->post('pax_surname');
			$pax_sex = $this->input->post('pax_sex');
			$pax_phone = $this->input->post('pax_phone');
			$pax_tc_number = $this->input->post('pax_tc_number');
			$pax_email = $this->input->post('pax_email');
			$pax_miles_number = $this->input->post('pax_miles_number');
			$pax_wheel_chair = $this->input->post('pax_wheel_chair');
			$passengers = array();
			$pax_count = $this->session->userdata('search_form_adults') + $this->session->userdata('search_form_children') + $this->session->userdata('search_form_elders') + $this->session->userdata('search_form_students') + $this->session->userdata('search_form_military');
			for ($i = 0; $i < $pax_count; $i++) {
				array_push($passengers, array(
                    'paxType' => $pax_type[$i],
                    'isMale' => $pax_sex[$i],
                    'name' => $pax_name[$i],
                    'surname' => $pax_surname[$i],
                    'milesMemberId' => $pax_miles_number[$i],
                    'wheelChairServiceType' => $pax_wheel_chair[$i]));
			}
			//print_r($passengers);exit;
			$this->session->set_userdata('passengers', $passengers);
			$infants = array();
			$j = 1;
			$b = 0;
			for ($i = $pax_count; $i < $this->session->userdata('search_form_infants') + $pax_count; $i++) {

				$pax_dob = $this->input->post('pax_dob');
				array_push($infants, array(
                    'relatedPassengerNo' => $j++,
                    'isMale' => $pax_sex[$i],
                    'name' => $pax_name[$i],
                    'surname' => $pax_surname[$i],
                    'birthdate' => $this->commonlibrary->get_date_for_wd($pax_dob[$b++])));
			}
			$this->session->set_userdata('infants', $infants);
			// decide to create ticket or create reservation first
			$flight_time = $this->session->userdata('first_flight_time');
			$time_pos = 0;
			if ($flight_time[2] == '-') {
				$time_pos = 3;
			}
			$now = time();
			$fdate = date("d-m-Y", strtotime($this->session->userdata('search_form_depart_on_ui'))) . ' ' . substr($flight_time, $time_pos, 2) . ':' . substr($flight_time, $time_pos + 2, 2) . ':00';
			$diff = strtotime($fdate) - $now;

			$pnr = 'TICKET'; // pnr olusmayan durumlar icin ticket yazilacak
			$this->session->set_userdata('surname', $pax_surname[0]);
			if ($diff > (48 * 60 * 60)) {
				$this->session->set_userdata('reserve_first', 1);
				// create reservation
				$reservation_xml = $this->websdom_api->call_create_reservation($this->session->userdata('agency_tk_user'), $this->session->userdata('agency_tk_pass'), $this->session->userdata('segment_data'), $passengers, $infants, $pax_phone, $receivedField = 'TODO', $this->session->userdata('agency_email'), $this->session->userdata('agency_phone'), $this->session->userdata('agency_remark'));
				$exception = $reservation_xml->xpath('//Exception');
				if (count($exception) > 0) {
					$err  = '<pre>ERROR OCCURED<BR>-------------';
					$err .= '<BR>Code       :' . $exception[0]->code;
					$err .= '<BR>Descriptino:' . $exception[0]->description;
					$err .= '<BR>Detail     :' . $exception[0]->details;
					$err .= '</pre>';
					show_error('İşleminizde bir hatası oluştu. Lütfen tekrar deneyiniz.<br/>'.$err);
				} else {
					$pnr = (string) $reservation_xml->PnrNumber;
					$this->session->set_userdata('time_limit', $reservation_xml->TimeLimit->date .' '. substr($reservation_xml->TimeLimit->time,0,2) .':'. substr($reservation_xml->TimeLimit->time,-2));
					$data['pnr_xml'] = $this->websdom_api->call_get_pnr($this->session->userdata('agency_tk_user'), $this->session->userdata('agency_tk_pass'), $pnr);
				}
			} else {
				$this->session->set_userdata('reserve_first', 0);
			}

			$data['pnr']=$pnr;
			$this->session->set_userdata('pnr', $pnr);
			// initiate a sale record in database
			$sql_data = array(
                'session_id' => $this->session->userdata('session_id'),
                'pnr' => $pnr,
                'amount' => str_replace(',', '', $this->session->userdata('total_fare')),
                'phone' => $pax_phone,
                'email' => $pax_email,
				'timestamp' => date('Y-m-d H:i:s'),
				'client_ip' => $_SERVER['REMOTE_ADDR'],
			);
			$this->db->insert('sales', $sql_data);
			$pax_count = $this->session->userdata('search_form_adults') + $this->session->userdata('search_form_children') + $this->session->userdata('search_form_elders') + $this->session->userdata('search_form_students')  + $this->session->userdata('search_form_infants') + $this->session->userdata('search_form_military');
			$this->session->set_userdata('pax_count',$pax_count);

			$submit = $this->input->post('submit');
			$data['sale']=1;
			if ($submit[0] != 'R') {
				$data['sale']=0;
				$this->callbank();
			}
			else {
				$this->template->write('title', $this->lang->line('good_flight'));
				$this->template->write_view('left_side_bar_bottom', 'content/callcenter');
				$this->template->write_view('content', 'show_pnr_content', $data);
				$this->template->render();
			}
		}
	}

	public function callbank() {
		$bank_url = $this->config->item('is_bank_url');
		//$bank_url = base_url() . 'babank.php';
		$client_id = $this->config->item('is_bank_client_id');
		$store_key = $this->config->item('is_bank_store_key');
		$store_type = $this->config->item('is_bank_store_type');

		$amount = str_replace(',', '', $this->session->userdata('total_fare'));
		$order_id = uniqid();
		$okUrl = site_url('/bookflight/success3d');
		$failUrl = site_url('/bookflight/fail3d');
		$rnd = microtime();
		$islemtipi="Auth";

		$taksit='';
		$firmaadi = $this->session->userdata('agency_remark');

		$hashstr = $client_id . $order_id . $amount . $okUrl . $failUrl . $islemtipi . $taksit . $rnd . $store_key;
		$hash = base64_encode(pack('H*', sha1($hashstr)));

		$form_fields = array(
                'clientid' => $client_id,
                'firmaadi' => $firmaadi,
                'amount' => $amount,
                'oid' => $order_id,
                'okUrl' => $okUrl,
                'failUrl' => $failUrl,
				'currency' => '949',
                'islemtipi' => $islemtipi,
                'taksit' => $taksit,
                'rnd' => $rnd,
                'hash' => $hash,
                'storetype' => $store_type,
                'lang' => 'tr',
                'refreshtime' => '1',
				'Fismi' => 'mavielma',
				'faturaFirma' => '',
				'Fadres' => 'XXX',
				'Fadres2' => 'XXX',
				'Fil' => 'XXX',
				'Filce' => 'XXX',
				'Fpostakodu' => 'XXX',
				'tel' => 'XXX',
				'fulkekod' => 'XXX',
				'nakliyeFirma' => 'XXX',
				'tismi' => 'XXX',
				'tadres' => 'XXX',
				'tadres2' => 'XXX',
				'til' => 'XXX',
				'tilce' => 'XXX',
				'tpostakodu' => '',
				'tulkekod' => 'tr',
		);

		$sql_data = array('order_id' => $order_id);
		$this->db->where('pnr', $this->session->userdata('pnr'));
		$this->db->update('sales', $sql_data);

		$this->load->helper('form');
		echo
            '<html><head>',
            '<script type="text/javascript" src="/js/jquery-1.7.1.min.js"></script>',
            '<script type="text/javascript" src="/js/jquery-ui-1.8.17.custom.min.js"></script>',
            '</head><body>',
		//generate the form,
		//form_open(base_url() . 'babank.php', array('id' => 'gateway')),
		form_open($bank_url, array('id' => 'gateway')),
		form_hidden($form_fields),
		form_close(),
            '<script>$("#gateway").submit();</script>',
            '</body></html>';
	}

	public function payfly() {
		if (!$this->session->userdata('logged_in')) {
			redirect('login');
		}
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');


		$this->form_validation->set_rules('pax_phone', $this->lang->line('phone'), 'required|min_length[7]|max_length[20]');
		$this->form_validation->set_rules('pax_email', $this->lang->line('e_mail'), 'trim');
		$this->form_validation->set_rules('pax_corporate_pin', $this->lang->line('corporate_pin'), 'trim||max_length[11]');

		$this->form_validation->set_rules('receipt_is_company', 'receipt_is_company', 'trim');
		$this->form_validation->set_rules('receipt_address', $this->lang->line('adress'), 'required|max_length[60]');
		$this->form_validation->set_rules('receipt_city', $this->lang->line('city'), 'required|max_length[30]');
		$this->form_validation->set_rules('receipt_country', $this->lang->line('country'), 'required|max_length[30]');
		$this->form_validation->set_rules('receipt_zip_code', $this->lang->line('zip_code'), 'required|max_length[10]');
		$this->form_validation->set_rules('receipt_tc_number', $this->lang->line('tc_identity'), 'trim|numeric|max_length[15]');
		if ($this->input->post('receipt_is_company') == true) {
			$this->form_validation->set_rules('receipt_company_name', $this->lang->line('company_name'), 'required|max_length[60');
			$this->form_validation->set_rules('receipt_tax_department', $this->lang->line('tax_department'), 'required|max_length[60]');
			$this->form_validation->set_rules('receipt_tax_number', $this->lang->line('tax_number'), 'required|numeric|max_length[15]');
		}
		$this->form_validation->set_rules('read_understood', $this->lang->line('read_understood'), 'required');

		if ($this->form_validation->run() == FALSE) {

			$pnr = $this->input->get('pnr');
			$pnr = !empty($pnr)?$pnr:$this->input->post('pnr');
			$pnr = $this->commonlibrary->to_en_upper($pnr);
			$surname = $this->input->get('surname');
			$surname = !empty($surname)?$surname:$this->input->post('surname');
			$surname = $this->commonlibrary->to_en_upper($surname);

			$pnr_xml = $this->websdom_api->call_get_pnr_fare($this->session->userdata('agency_tk_user'),$this->session->userdata('agency_tk_pass'),$pnr,$surname,false);

			$pax_sum=0;
			$val = $pnr_xml->xpath('//PassengerTypeCount/adult');$pax_sum+=$val[0];$adults=$val[0];
			$val = $pnr_xml->xpath('//PassengerTypeCount/overaged');$pax_sum+=$val[0];$elders=$val[0];
			$val = $pnr_xml->xpath('//PassengerTypeCount/student');$pax_sum+=$val[0];$students=$val[0];
			$val = $pnr_xml->xpath('//PassengerTypeCount/child');$pax_sum+=$val[0];$children=$val[0];
			$val = $pnr_xml->xpath('//PassengerTypeCount/infant');$pax_sum+=$val[0];$infants=$val[0];

			$data_fare['fare_arr'] = $this->get_fares_with_du($pnr_xml->xpath('//fareItem'),
			$pnr_xml->xpath('//grandTotal'),
			$pnr_xml->xpath('//segment'),$adults,$children,$students,$elders);
			$data['pnr_xml']=$pnr_xml;

			$this->session->set_userdata('pnr',$pnr);
			$this->session->set_userdata('surname',$surname);


			$this->session->set_userdata('pax_count',$pax_sum);

			$this->template->write('title', 'Profile!');
			$this->template->write_view('left_side_bar_top', 'book_flight_fare', $data_fare);
			$this->template->write_view('left_side_bar_bottom', 'content/3dsecure');
			$this->template->write_view('content', 'payfly',$data);
			$this->template->render();
		} else {


			$session_array = array(
				'pax_corporate_pin' => $this->input->post('pax_corporate_pin'),
				'receipt_is_company' => $this->input->post('receipt_is_company'),
                'receipt_address' => $this->input->post('receipt_address'),
                'receipt_city' => $this->input->post('receipt_city'),
                'receipt_country' => $this->input->post('receipt_country'),
                'receipt_zip_code' => $this->input->post('receipt_zip_code'),
                'receipt_company_name' => $this->input->post('receipt_company_name'),
                'receipt_tax_department' => $this->input->post('receipt_tax_department'),
                'receipt_tax_number' => $this->input->post('receipt_tax_number'),
                'receipt_tc_number' => $this->input->post('receipt_tc_number'),
			);
			$this->session->set_userdata($session_array);

			$this->session->set_userdata('reserve_first', 1);

			$this->callbank();
		}

	}

	public function fail3d() {

		$response = array("AuthCode","Response","HostRefNum","ProcReturnCode","TransId","ErrMsg");
		$mdStatus = $_POST["mdStatus"];
		$ErrMsg = $_POST["mdErrorMsg"];

		$heading = $this->lang->line('payment_err_header');
		$message = $this->lang->line('payment_err_message');
		$message .= '<br/><br/><b>Hata kodu:</b>' . $mdStatus . '<br/><b>Hata Açıklaması:</b>' . $ErrMsg .'.';


		$message .= '<pre style="visibility:hidden;">';
		foreach($_POST as $key => $value)
		{
			$check=1;
			for($i=0;$i<6;$i++)
			{
				if($key == $response[$i])
				{
					$check=0;
					break;
				}
			}
			if($check == 1)
			{
				$message .= $key.':'.$value;
			}
		}
		$message .= '</pre>';
		log_message('error',$message);
		show_error($message,200,$heading);
	}

	public function success3d() {

		$hashparams = $_POST["HASHPARAMS"];
		$hashparamsval = $_POST["HASHPARAMSVAL"];
		$hashparam = $_POST["HASH"];
		$paramsval = '';
		$index1 = 0;
		$index2 = 0;

		while($index1 < strlen($hashparams)) {
			$index2 = strpos($hashparams,":",$index1);
			$vl = $_POST[substr($hashparams,$index1,$index2- $index1)];
			if($vl == null)
			$vl = "";
			$paramsval = $paramsval . $vl;
			$index1 = $index2 + 1;
		}
		$storekey = $this->config->item('is_bank_store_key');
		$hashval = $paramsval.$storekey;
		$hash = base64_encode(pack('H*',sha1($hashval)));
		if($paramsval != $hashparamsval || $hashparam != $hash)	{

			$order_id = $_POST['oid'];
			$data['order_id'] = $order_id;
			
			$mdStatus = $_POST["mdStatus"];
			$ErrMsg = $_POST["mdErrorMsg"];
			$data['auth_code'] = $_POST['AuthCode'];
			// End Welcome bank

			$sql_data = array(
            'order_id' => $order_id,
            'state' => 'PAYMENT_COMLETE',
			'timestamp' => date('Y-m-d H:i:s'),
			);
			$this->db->insert('sales_state', $sql_data);

			$sql_data = array(
            'auth_code' => $_POST['AuthCode']
			);
			$this->db->where('order_id', $order_id);
			$this->db->update('sales', $sql_data);

			if ($mdStatus == 1 || $mdStatus == 2 || $mdStatus == 3 || $mdStatus == 4) {
				$receiptDatas = array();
				for ($i = 0; $i < $this->session->userdata('pax_count'); $i++) {
					if ($this->session->userdata('receipt_is_company') == true) {
						array_push($receiptDatas, array(
                        'isCompany' => $this->session->userdata('receipt_is_company'),
                        'address' => $this->session->userdata('receipt_address'),
                        'city' => $this->session->userdata('receipt_city'),
                        'country' => $this->session->userdata('receipt_country'),
                        'zipCode' => $this->session->userdata('receipt_zip_code'),
                        'companyName' => $this->session->userdata('receipt_company_name'),
                        'vergiDairesi' => $this->session->userdata('receipt_tax_department'),
                        'vergiNo' => $this->session->userdata('receipt_tax_number'),
                        'trIdCardNo' => $this->session->userdata('receipt_tc_number')));
					} else {
						array_push($receiptDatas, array(
                        'isCompany' => $this->session->userdata('receipt_is_company'),
                        'address' => $this->session->userdata('receipt_address'),
                        'city' => $this->session->userdata('receipt_city'),
                        'country' => $this->session->userdata('receipt_country'),
                        'zipCode' => $this->session->userdata('receipt_zip_code'),
                        'trIdCardNo' => $this->session->userdata('receipt_tc_number')));
					}
				}
				if ($this->session->userdata('reserve_first')) {
					// ticket the reservation
					$ticket_xml = $this->websdom_api->call_ticket_reservation($this->session->userdata('agency_tk_user'), $this->session->userdata('agency_tk_pass'), $this->session->userdata('pnr'), $this->session->userdata('surname'), $receiptDatas, $this->session->userdata('search_form_cip'), $this->session->userdata('pax_corporate_pin'), $needTicketPrint = false);
				} else {
					$ticket_xml = $this->websdom_api->call_create_ticket(
					$this->session->userdata('agency_tk_user'), $this->session->userdata('agency_tk_pass'), $this->session->userdata('segment_data'), $this->session->userdata('passengers'), $this->session->userdata('infants'), $this->session->userdata('agency_phone'), $receivedField = 'TODO', $this->session->userdata('agency_email'), $this->session->userdata('agency_phone'), $receiptDatas, $this->session->userdata('agency_remark'), $this->session->userdata('search_form_cip'), $this->session->userdata('pax_corporate_pin'), $needTicketPrint = false);
				}
				$exception = $ticket_xml->xpath('//Exception');
				if (count($exception) > 0) {
					$err  =  'PNR:' . $this->session->userdata('pnr') . ' Bank Authorization:' . $_POST['AuthCode'] . '<br/>';
					$err .= '<pre>ERROR OCCURED<BR>-------------';
					$err .= '<BR>Code       :' . $exception[0]->code;
					$err .= '<BR>Descriptino:' . $exception[0]->description;
					$err .= '<BR>Detail     :' . $exception[0]->details;
					$err .= '</pre>';
					show_error('İşleminizde bir hatası oluştu. Lütfen tekrar deneyiniz.<br/>'.$err);
				} else {

					$pnr = (string) $ticket_xml->PnrNumber;
					$data['pnr']=$pnr;

					if (!$this->session->userdata('reserve_first')) {
						$sql_data = array('pnr' => $pnr);
						$this->db->where('order_id', $order_id);
						$this->db->update('sales', $sql_data);
					}

					$sql_data = array(
                    'order_id' => $order_id,
                    'state' => 'WD_CREATE_TICKET_RESPONDED',
					'timestamp' => date('Y-m-d H:i:s'),
					);
					$this->db->insert('sales_state', $sql_data);

					// call the PNR
					$data['pnr_xml'] = $this->websdom_api->call_get_pnr_fare($this->session->userdata('agency_tk_user'), $this->session->userdata('agency_tk_pass'), $pnr, $this->session->userdata('surname'), $this->session->userdata('search_form_cip'));

					$sql_data = array(
                    'order_id' => $order_id,
                    'state' => 'WD_GET_PNR_RESPONDED',
					'timestamp' => date('Y-m-d H:i:s'),
					);
					$this->db->insert('sales_state', $sql_data);


					$pnr_view = $data['pnr_xml']->xpath('//pnrView');
					$pnr_view = $pnr_view[0];
					$pnr_fares = $this->websdom_api->get_fare_from_pnr($pnr_view);
					$passengers = $data['pnr_xml']->xpath('//Passenger');
					$ticket_numbers = $this->websdom_api->get_ticket_numbers_from_pnr($pnr_view);

					$pax_order=0;
					$val = $data['pnr_xml']->xpath('//PassengerTypeCount/adult');$this->insert_ticket_to_db($pnr,$ticket_numbers, $passengers,$pnr_fares,'ADT',$val[0],$pax_order);$pax_order+=$val[0];
					$val = $data['pnr_xml']->xpath('//PassengerTypeCount/overaged');$this->insert_ticket_to_db($pnr,$ticket_numbers, $passengers,$pnr_fares,'CD',$val[0],$pax_order);$pax_order+=$val[0];
					$val = $data['pnr_xml']->xpath('//PassengerTypeCount/student');$this->insert_ticket_to_db($pnr,$ticket_numbers, $passengers,$pnr_fares,'ZS',$val[0],$pax_order);$pax_order+=$val[0];
					$val = $data['pnr_xml']->xpath('//PassengerTypeCount/child');$this->insert_ticket_to_db($pnr,$ticket_numbers, $passengers,$pnr_fares,'CNN',$val[0],$pax_order);$pax_order+=$val[0];
					$val = $data['pnr_xml']->xpath('//PassengerTypeCount/infant');$this->insert_ticket_to_db($pnr,$ticket_numbers, $passengers,$pnr_fares,'INF',$val[0],$pax_order);

					$data['sale']=0;

					$this->template->write('title', $this->lang->line('good_flight'));
					$this->template->write_view('left_side_bar_bottom', 'content/callcenter');
					$this->template->write_view('content', 'show_pnr_content', $data);
					$this->template->render();
				}
			} else {

				$heading = $this->lang->line('payment_err_header');
				$message = $this->lang->line('payment_err_message');
				$message .= '<br/><b>Hata Detayı:</b>' . $mdStatus . ':' . $ErrMsg . '.';
				show_error($message,1,$heading);
			}
		}
	}


	function check_infant_age() {
		$ages = $this->input->post('pax_dob');
		foreach ($ages as $age) {
			$diff = time() - strtotime($age);
			if ($diff > (60*60*24*365*2)) {
				$this->form_validation->set_message('check_infant_age', $this->lang->line('profile.err.invalid_infant_age'));
				return FALSE;
			}
		}
		return TRUE;
	}

	function check_miles($value) {
		$miles = $this->input->post('pax_miles_number');
		foreach ($miles as $milesid) {
			if (strlen($milesid) > 0 && strlen($milesid) != 11) {
				$this->form_validation->set_message('check_miles', $this->lang->line('profile.err.miles_smiles'));
				return FALSE;
			}

		}
		return TRUE;
	}

	function get_fares_with_du($fares,$grand_total,$segments,$adults,$children,$student,$elders) {
		$total_du = 0;
		$fare_arr = array();
		$is_flight_full_aj = TRUE;
		foreach($segments as $segment) {
			$is_flight_full_aj = ((substr($segment['flightNumber'],0,3) == 'TK7' && strlen($segment['flightNumber']) == 6) || (substr($segment['flightNumber'],0,3) == 'TK9' && strlen($segment['flightNumber']) == 6))  ? TRUE : FALSE;
			if ($is_flight_full_aj == FALSE) break;
		}
		if ($is_flight_full_aj) {
			$du_to_collect = 10; //TODO: 10 TL for AJ
		} else {
			$du_to_collect = 15; //TODO: 15 TL for TK
		}
		$this->session->set_userdata('DU_TO_COLLECT', $du_to_collect);
		foreach ($fares as $fareItem) {
			switch (((string) $fareItem->passengerDescription)) {
				case 'CIP':
				case 'ADT':
					$du = $adults * $du_to_collect;
					break;
				case 'CNN':
					$du = $children * $du_to_collect;
					break;
				case 'CD':
					$du = $elders * $du_to_collect;
					break;
				case 'ZS':
					$du = $student * $du_to_collect;
					break;
				case 'INF':
					$du = 0;
					break;
			}
			$tot_fare = (float)$fareItem->subtotal + $du;
			$total_du+=$du;
			$du = number_format($du, 2, '.', ',');
			$arr = array('pax_type' => ((string) $fareItem->passengerDescription), 'fare' => ((string) $fareItem->fare), 'tax' => ((float) $fareItem->taxes), 'du' => $du, 'subtotal' => $tot_fare, 'currency' => (string) $fareItem->currency);
			array_push($fare_arr, $arr);
		}
		$total = (float)$grand_total[0]->total + $total_du;
		$this->session->set_userdata('total_du', number_format($total_du, 2, '.', ','));
		$this->session->set_userdata('total_fare', number_format($total, 2, '.', ','));
		$this->session->set_userdata('currency', 'TL');
		return $fare_arr;
	}
	function insert_ticket_to_db($pnr,$ticket_numbers, $passengers,$pnr_fares,$pax_type,$pax_count,$pax_order) {
		for ($i = 0; $i < $pax_count; $i++) {
			$sql_data = array(
                        'PNR' => $pnr,
                        'PAXTYPE' => $pax_type,
                        'NAME' => (string)$passengers[$pax_order+$i]->name,
                        'SURNAME' => (string)$passengers[$pax_order+$i]->surname,
                        'TICKETNUMBER' => $ticket_numbers[$pax_order+$i]['ticket'],
                        'CONJUNCTIONS' => $ticket_numbers[$pax_order+$i]['conj'],
                        'BASEFARE' => $pnr_fares[$pax_order]['fare'],
                        'TAXES' => ($pax_type=='INF'? 0 : $pnr_fares[$pax_order]['tax']),
                        'SERVICECHARGE' => ($pax_type=='INF'? 0 : $this->session->userdata('DU_TO_COLLECT')),
                        'TOTALFARE' => $pnr_fares[$pax_order]['total'],
						'timestamp' => date('Y-m-d H:i:s'),
			);
			$this->db->insert('tickets', $sql_data);
		}
	}
}